package com.lagou.edu;

import com.lagou.edu.anotition.MyAutowired;
import com.lagou.edu.anotition.MyService;
import com.lagou.edu.anotition.MyTransactional;
import com.lagou.edu.factory.ProxyFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class MyApplicationContext implements ApplicationContext {



    // 2:通过反射技术实例化对象并且存储待用（map集合）
    // 3:实例化
    // 4:依赖注入

    //包名
    private String packageName;
    //存放beans
    private ConcurrentHashMap<String, Object> beans = new ConcurrentHashMap<>();

    static {

    }

    public MyApplicationContext(String packageName) {
        this.packageName = packageName;
        initBeans();
    }

    // 1:读取解析xml，获取包扫描路径
    private void initBeans() {
        List<Class> classList = getClasses(packageName);
        findClassUseMyAnnotation(classList);
    }

    //查找包下面的类，返回classList集合
    private List<Class> getClasses(String packageName) {
        List<Class> classList = new ArrayList<>();
        String packageDirName = packageName.replace(".", "/");
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String protocol = url.getProtocol();
                if (protocol.equals("file")) {
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    //查找包下面的class
                    findAndAddClassesInPackageByFile(packageName, filePath, classList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classList;
    }

    private void findAndAddClassesInPackageByFile(String packageName, String filePath, List<Class> classList) {
        File dir = new File(filePath);
        //选出文件夹下面所有的文件
        File[] files = dir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return (file.isDirectory() || file.getName().endsWith(".class"));
            }
        });
        //递归，查找文件
        for (File file : files) {
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), classList);
            } else {
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    Class classInfo = Class.forName(packageName + "." + className);
                    MyService myService = (MyService) classInfo.getAnnotation(MyService.class);//.getDeclaredAnnotation(MyService.class);
                    if(myService!=null){
                        //判断MyService注解上是否有自定义对象ID
                        if(StringUtils.isEmpty(myService.value())){
                            //由于getName获取的是全限定类名，所以要分割去掉前面包名部分
                            String[] names = classInfo.getName().split("\\.");
                            classInfo.newInstance();
                            //map.put(names[names.length-1], object);
                        }else{
                           // map.put(service.value(), object);
                        }
                        classList.add(Class.forName(packageName + "." + className));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 获取包下面的自定义注解的类
    private void findClassUseMyAnnotation(List<Class> classList) {
        try{
            for (Class aClass : classList) {
                classToObjectIntoBeans(aClass, classList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void classToObjectIntoBeans(Class aClass, List<Class> classList) {
        Object obj = null;

        try{
            if(aClass.isInterface()){
                for(Class implClass : classList) {
                    if (implClass.isInterface()) {
                        continue;
                    }
                    Class fieldClassCopy = implClass.getClassLoader().loadClass(aClass.getName());
                    if (fieldClassCopy.isAssignableFrom(implClass)) {
                        Constructor[] constructors = implClass.getConstructors();
                        for(Constructor constructor : constructors){
                            int parameterCount = constructor.getParameterCount();
                            if(parameterCount==0){
                                obj = constructor.newInstance();
                            }
                        }
                        break;
                    }
                }
            } else {
                Constructor[] constructors = aClass.getConstructors();
                for(Constructor constructor : constructors){
                    int parameterCount = constructor.getParameterCount();
                    if(parameterCount==0){
                        obj = constructor.newInstance();
                    }
                }
            }
            if (obj != null) {
                beans.put(aClass.getSimpleName(), obj);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public Object getBean(String beanName, ApplicationContext customApplicationContext) {
        Object beanObject = beans.get(beanName);
        try{
            referenceBindObject(beanObject);
        }catch (Exception e){
            e.printStackTrace();
        }

        Class aClass = beanObject.getClass();
        Annotation annotation = aClass.getAnnotation(MyTransactional.class);
        if (annotation != null) {
            ProxyFactory proxyFactory = (ProxyFactory) customApplicationContext.getBean("ProxyFactory", customApplicationContext);
            beanObject = proxyFactory.getJdkProxy(beanObject);
        }
        return beanObject;
    }

    // 使用反射读取类的属性,赋值信息
    private Object referenceBindObject(Object beanObject) throws ClassNotFoundException {
        Class<?> c =Class.forName(beanObject.toString());
        Class beanClass = beanObject.getClass();
        Field[] declaredFields = beanClass.getDeclaredFields();
        try {
            for (Field field : declaredFields) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                MyAutowired filedAnnotation = field.getAnnotation(MyAutowired.class);
                if (filedAnnotation == null) {
                    System.out.println(beanClass.getName() + "类中的" + field.getName() + "字段,该字段上没有加注解");
                    break;
                }
                Class fieldClass = field.getType();
                String classSimpleName = fieldClass.getSimpleName();
                Object fieldObject = beans.get(classSimpleName);
                Object object = referenceBindObject(fieldObject);
                field.set(beanObject, object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return beanObject;
    }
}